package com.chuisha;

import cn.hutool.core.lang.UUID;
import org.slf4j.MDC;
import org.springframework.util.StringUtils;

import java.util.Map;
import java.util.Objects;
import java.util.concurrent.Callable;

public class ThreadMDCUtil {

    public static final String TRACE_ID = "TRACE_ID10";

    public static String getTraceId(){
        return MDC.get(TRACE_ID);
    }

    public static String generatorTraceId(){
        return UUID.fastUUID().toString(true);
    }

    public static void setTraceIdIfAbsent(String traceId){
        if(MDC.get(TRACE_ID) == null){
            traceId = StringUtils.isEmpty(traceId) ? generatorTraceId() : traceId;
            MDC.put(TRACE_ID,traceId);
        }
    }

    /**
     * 用于父线程 向 线程池中提交任务时，将MDC中traceid传给子线程
     * @param callable
     * @param context
     * @return
     * @param <T>
     */
    public static <T> Callable<T> wrap(final Callable<T> callable, final Map<String,String> context){
        return () -> {
            if(Objects.isNull(context)){
                MDC.clear();
            }else {
                MDC.setContextMap(context);
            }
            setTraceIdIfAbsent(null);
            try {
                return callable.call();
            } finally {
                MDC.clear();
            }
        };
    }

    /**
     * 用于父线程 向 线程池中提交任务时，将MDC中traceid传给子线程
     * @param runnable
     * @param context
     * @return
     */
    public static Runnable wrap(final Runnable runnable,final Map<String,String> context){
        return () -> {
            if(Objects.isNull(context)){
                MDC.clear();
            }else {
                MDC.setContextMap(context);
            }
            setTraceIdIfAbsent(null);
            try {
                runnable.run();
            } finally {
                MDC.clear();
            }
        };
    }
}
